package com.myz.rabbitmq.controller;

import com.myz.rabbitmq.config.DelayedQueueConfig;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/*
* 发送延迟信息
* */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    // 发消息
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message){
        log.info("当前时间:{},发送一条信息给两个TTL队列:{}",new Date().toString(),message);
        // 发送消息ttl在消息队列处设置
        rabbitTemplate.convertAndSend("X","XA","消息来自ttl为5s的队列"+message);
        rabbitTemplate.convertAndSend("X","XB","消息来自ttl为10s的队列"+message);
        // 发送包含ttl时间的消息
        /*rabbitTemplate.convertAndSend("X","XB","消息来自ttl为10s的队列"+message,msg ->{
            msg.getMessageProperties().setExpiration("5000");
            return msg;
        });*/
    }
    // 发送包含ttl的消息
    @GetMapping("/sendMsg/{message}/{ttl}")
    public void sendMsg(@PathVariable String message,@PathVariable String ttl){
        // 发送包含ttl时间的消息
        log.info("当前时间:{},发送一条时长{}毫秒的信息给两个TTL队列:{}",new Date().toString(),ttl,message);
        rabbitTemplate.convertAndSend("X","XC","消息来自ttl为"+ttl+"的队列"+message,msg -> {
            msg.getMessageProperties().setExpiration(ttl);
            return msg;
        });
    }

    // 基于延迟队列插件发送消息
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendDelayMsg(@PathVariable String message,@PathVariable Integer delayTime){
        log.info("当前时间:{},发送一条时长{}毫秒的信息给延迟队列delayed.queue:{}",new Date().toString(),delayTime,message);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE,DelayedQueueConfig.DELAYED_ROUTING_KEY,"延迟为"+delayTime+"的消息:"+message,
                msg->{
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                });
    }
}
